package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkspaceService workspaceService;
    /**
     * 统计指定时间范围内的营业额
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin,LocalDate end) {
        //计算出从开始到结束日期的每一天，并将其封装成，日期，以逗号分隔，例如：2022-10-01,2022-10-02,2022-10-03

        List<LocalDate> dateList = new ArrayList<>();
        //计算日期，计算指定日期的后一天
        while(!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //计算每日的销售金额，
        List<Double> turnoverStatisticsList = new ArrayList<>();
        for(LocalDate localDate : dateList){
            //查询date对应的销售金额，销售金额是指订单状态为已完成的订单金额的总和
            //首先计算那一天的最开始的时间为00:00和最晚的时间为23:59
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            //查询每天从开始到一天结束，者之间订单的数量，使用map同时存储需要传递的参数，每天开始时间和关闭时间，和订单状态为已完成的订单
            Map map = new HashMap();
            map.put("begin",beginTime);
            map.put("end", endTime);
            map.put("status", Orders.COMPLETED);

            Double turnoverStatistics = orderMapper.sumByMap(map);

            turnoverStatistics = turnoverStatistics == null ? 0.0 : turnoverStatistics;
            //存放每天的营业额
            turnoverStatisticsList.add(turnoverStatistics);
        }


        //将dateList里面的数据封装成字符串格式
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .turnoverList(StringUtils.join(turnoverStatisticsList,","))
                .build();
    }

    /**
     * 统计指定时间区间内的用户数据
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {

        //存放从begin开始到end结束每天对应的日期
        List<LocalDate> dateList = new ArrayList<>();
        //计算日期，计算指定日期的后一天
        while(!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //存放每天的新增用户总数select count(id) from user where creat_time > ? and creat_time < ?
        List<Integer> newUserList = new ArrayList<>();

        //存放每天的总的用户数量select count(id) from user where creat_time > ?
        List<Integer> userList = new ArrayList<>();

        for(LocalDate date : dateList){
            LocalDateTime beginTime = LocalDateTime.of(date,LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date,LocalTime.MAX);

            Map map = new HashMap<>();
            //先统计总的用户数量，因为统计总的用户数量的sql语句条件简单，先查总的在查新增的
            map.put("end" ,endTime);

            Integer totalUser = userMapper.countByMap(map);
            map.put("begin" ,beginTime);
            Integer newUser = userMapper.countByMap(map);
            userList.add(totalUser);
            newUserList.add(newUser);

        }
        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .newUserList(StringUtils.join(newUserList,","))
                .totalUserList(StringUtils.join(userList,","))
                .build();
    }

    @Override
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        //存放从begin开始到end结束每天对应的日期
        List<LocalDate> dateList = new ArrayList<>();
        //计算日期，计算指定日期的后一天
        while(!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        //存放每天的已完成订单总数select count(id) from order where order_time > ? and order_time < ? status = ?
        List<Integer> completedOrderList = new ArrayList<>();

        //存放每天的总的订单数量select count(id) from order where order_time > ? and order_time < ?
        List<Integer> countOrderList = new ArrayList<>();

        for(LocalDate date : dateList){
            //开始时刻
            LocalDateTime beginTime = LocalDateTime.of(date,LocalTime.MIN);
            //结束时刻
            LocalDateTime endTime = LocalDateTime.of(date,LocalTime.MAX);

            Map map = new HashMap<>();
            map.put("begin" ,beginTime);
            map.put("end" ,endTime);
            //查询每天的订单总数
            Integer  totalOrders= orderMapper.countByMap(map);

            map.put("status", Orders.COMPLETED);
            //查询每天的有效订单数
            Integer completedOrders = orderMapper.countByMap(map);

            countOrderList.add(totalOrders);
            completedOrderList.add(completedOrders);
        }
        //计算从begin到end的这段时间内总的订单总数
        Integer totalOrder = 0;
        for(Integer order : countOrderList){
            totalOrder = totalOrder + order;
        }
        //计算从begin到end的这段时间内总的有效订单总数
        Integer validOrder = completedOrderList.stream().reduce(Integer::sum).get();
        //计算订单完成率
        Double orderCompletionRate = 0.0;
        if(totalOrder != 0){
            orderCompletionRate = validOrder.doubleValue() / totalOrder;
        }
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .orderCountList(StringUtils.join(countOrderList,","))
                .validOrderCountList(StringUtils.join(completedOrderList,","))
                .validOrderCount(validOrder)
                .totalOrderCount(totalOrder)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    @Override
    public SalesTop10ReportVO getSalesTop10ReportVO(LocalDate begin, LocalDate end) {

       //将LocalDate类型的数据转化为LocalDateTime类型
            LocalDateTime beginTime = LocalDateTime.of(begin,LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(end,LocalTime.MAX);
            //查询从begin到end结束这期间的销售菜品排名前十的数量
        List<GoodsSalesDTO> salesTop10 = orderMapper.searchTop10(beginTime, endTime);
        List<String> nameList = salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        String name = StringUtils.join(nameList, ",");
        List<Integer> numberList = salesTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String number = StringUtils.join(numberList, ",");

            //封装返回结果
        return SalesTop10ReportVO.builder()
                .nameList(name)
                .numberList(number)
                .build();
    }

    /**
     * 导出运营数据报表
     * @param response
     */
    @Override
    public void exportBusinessData(HttpServletResponse response) {

        //获取昨天和30天以前的日期
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);
        LocalDateTime beginTime = LocalDateTime.of(begin,LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end,LocalTime.MAX);
        //查询数据库，获取近30天的营业数据
        BusinessDataVO businessDataVO = workspaceService.getBusinessData(beginTime,endTime);
        //通过POI将数据写入Excel文件中
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        try{
            //基于模板文件创建一个新的Excel文件
            XSSFWorkbook excel = new XSSFWorkbook(in);
            //填充概览数据
            XSSFSheet sheet = excel.getSheet("Sheet1");

            sheet.getRow(1).getCell(1).setCellValue("时间：" + begin + "到" + end);
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());
            //填充明细数据

            for(int i = 0; i < 30; i ++){
                LocalDate date = begin.plusDays(i);
                BusinessDataVO businessDataVO1 = workspaceService.getBusinessData(LocalDateTime.of(date,LocalTime.MIN),LocalDateTime.of(date,LocalTime.MAX));
                row = sheet.getRow(i + 7);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessDataVO1.getTurnover());
                row.getCell(3).setCellValue(businessDataVO1.getValidOrderCount());
                row.getCell(4).setCellValue(businessDataVO1.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessDataVO1.getUnitPrice());
                row.getCell(6).setCellValue(businessDataVO1.getNewUsers());
            }
            //通过输出流将excel下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);
            //关闭资源
            out.close();
            excel.close();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}
